﻿//Eventos comunes

//Conteo de validaciones
var CountNumberField = {};
//Asignar valor al control numberfield
var setCountNF = function (numfield, newValue) {
    try {

        if (numfield) {
            if (typeof CountNumberField[numfield.id] == "undefined")
                CountNumberField[numfield.id] = 0;

            if (CountNumberField[numfield.id] == 0 && newValue == -1) {
                CountNumberField[numfield.id] = 0;
                newValue = 0;
            }

            CountNumberField[numfield.id] = CountNumberField[numfield.id] + newValue;
            numfield.setValue(CountNumberField[numfield.id]);
        }
    } catch (jsbug) {
        AppGlobalJs.showBug("setCountNF: " + jsbug);
    }
};
var SetNumberFieldControl = function (item, newValue, oldValue, numfield) {
    try {

        var numOpc = -1;
        if (newValue) {
            numOpc = 1;
        }
        setCountNF(numfield, numOpc);


    } catch (jsbug) {
        AppGlobalJs.showBug("SetNumberFieldControl: " + jsbug);
    }
};
//Asignar allowBlank= true a elementos textfields
var SetAllowBlankTxt = function (items) {
    try {
        for (var index = 0; index < items.length; index++) {
            var cpm = Ext.getCmp(items[index]);
            if (cpm) {

                cpm.allowBlank = false;
            }
        }



    } catch (jsbug) {
        AppGlobalJs.showBug("SetAllowBlankTxt: " + jsbug)
    }
};
//Vizualizar texfiel y asignar valor de obligatoriedad
var MostrarControlObligatorio = function (item, newValue, oldValue, control, numfield) {
    try {
        var numOpc = -1;
        if (newValue) {
            numOpc = 1;
            control.show();
        }
        else {
            control.hide();
        }
        //Para validacion de elementos
        control.allowBlank = !newValue;
        setCountNF(numfield, numOpc);

    } catch (jsbug) {
        AppGlobalJs.showBug("MostrarControlObligatorio: " + jsbug);
    }
};
var setHidenComentario = function (items, rol, opr) {
    try {
        //             
        for (var index in items) {

            var txt_area = App.frmExpediente.getForm().findField(items[index]);
            if (txt_area != null) {
                var btn = Ext.getCmp("btn_" + items[index]);
                if (rol == 'PROMOTOR') {
                    if (opr == 'H') {
                        txt_area.hide();
                    }
                    else {

                        if (txt_area.getValue() != "") {
                            txt_area.readOnly = true;
                            txt_area.show();
                        }
                        else {
                            txt_area.hide();
                        }

                    }
                    if (btn != null)
                        btn.hide();

                }
                else {
                    txt_area.show();
                    if (txt_area.getValue() != "") {
                        txt_area.enable();
                        txt_area.readOnly = false;
                    }
                    else {
                        txt_area.disable();
                    }
                    if (btn != null)
                        btn.show();

                }
            }

        }

    } catch (jsbug) {
        AppGlobalJs.showBug("setHidenComentario: " + jsbug)
    }
};
var DatosOtros = function (item, newValue, oldValue) {
    try {
        //alert('cambio');
    } catch (jsbug) {
        AppGlobalJs.showBug("DatosOtros: " + jsbug)
    }
};
//Setear combox de localidad de expediente
var SetLocalidadExpediente = function (idProv, idCanton, idParroquia) {
    try {

        App.direct.GetCanton(idProv, idCanton, {
            success: function (result) {
                var cpm = Ext.getCmp('cbbProvincia');
                if (cpm) {

                    cpm.select(idProv, true);
                }

                cpm = Ext.getCmp('cbbCanton');
                if (cpm) {
                    cpm.getStore().loadData(result.ListCanton);
                    cpm.select(idCanton, true);
                }

                cpm = Ext.getCmp('cbbParroquia');
                if (cpm) {
                    cpm.getStore().loadData(result.ListParroq);
                    cpm.select(idParroquia, true);
                }

                cpm = Ext.getCmp('cbxNacionalidad');
                if (cpm) {

                    cpm.select(idNacionalidad, true);
                }
            },
            eventMask: {
                showMask: true,
                minDelay: 500
            }
        });
    } catch (jsbug) {
        AppGlobalJs.showBug("SetLocalidad: " + jsbug);
    }
};
var ClerValidInfo = function () {
    try {
        var idState = "#formErrorState_" + "0";//+ index;
        var formCmp = App.panContenedorDatosFicha;
        var errorCmp = formCmp.dockedItems.get(0).down(idState);//get(1)
        var baseCls = errorCmp.baseCls;
        errorCmp.removeCls(baseCls + '-valid');

        errorCmp.update("");

    } catch (jsbug) {
        AppGlobalJs.showBug("ClaerValidInfo: " + jsbug);

    }
};
//Validar informacion
var SetValidInfo = function (form, index, appGeo,msg) {
    try {

        var infoAddPlus = '';      
        var nCountGrid  = false
        //(typeof(App.pnlGeoReferencia.getBody().App)!='undefined')?App.pnlGeoReferencia.getBody().App.btnFlag.disabled:true);
        if (typeof (appGeo.getBody()) == 'undefined') {

            nCountGrid = true;
        }
        else
        {
            if (typeof (appGeo.getBody().App) != 'undefined')
                nCountGrid = appGeo.getBody().App.btnFlag.disabled;
            else
                nCountGrid = true;
        }
        //Metodo donde se debe agregar puntos de referencia
        if (typeof (msg) != 'undefined') {
            if (msg != '') {
                infoAddPlus = msg + '. ';
                nCountGrid = false;
            }
        }
        var idState = "#formErrorState_" + "0";//+ index;
        var formCmp = App.panContenedorDatosFicha;
        var errorLabel = [];
        var errors = AppGlobalJs.GetListErrors(form);
        var errorCmp = formCmp.dockedItems.get(0).down(idState);//get(1)
        var baseCls = errorCmp.baseCls;
        var tip = errorCmp.tooltips[0];
        if (errors.length != 0) {
            errorCmp.addCls(baseCls + '-invalid');
            errorCmp.removeCls(baseCls + '-valid');
            errorCmp.update("Formulario con errores");
            tip.setDisabled(false);
            if (index != 0) {
                Ext.Array.forEach(errors, function (error) {
                    if (error.name.substring(0, 1) == "*")
                        errorLabel.push({ name: error.name.substring(1), error: 'Se requiere que seleccione al menos una opción' });
                });
                //tip.update(errorCmp.bin[0].apply(errorLabel));
            }
           
        } else
        {
            errorCmp.addCls(baseCls + '-valid');
            errorCmp.removeCls(baseCls + '-invalid');
            errorCmp.update("Formulario valido");
            tip.setDisabled(true);
            //
        }
        var flag = form.isValid();
        if (flag && index == 0) //Tab georeferencia
        {
            if (nCountGrid == true) {//Boton disables del panel
                flag = false;
                Ext.Msg.show({
                    title: 'Aviso',
                    msg: "Datos invalidos, debe ingresar todos los puntos de referencia que tiene en el certificado de intersección",
                    buttons: Ext.Msg.ERROR,
                    animEl: 'elId'
                });

            }

        }
        else {
            if (flag == false) {
                var infoAdd = " <ol>";
                var infodeta = "";
                /*
                <ol> 
                     <li>Uno</li> 
                     <li>Dos</li> 
                     <li>Tres</li> 
                </ol> 
                */
                var iCountErrorTxt = 0;
                var iCountErrorCodig = 0;
                Ext.Array.forEach(errors, function (error) {

                    if (error.name.substring(0, 1) == "*") {
                        infodeta = error.name.substring(1, error.name.length);
                    }
                    else {
                        if (error.name.indexOf("txt_") != -1 & iCountErrorTxt == 0) {
                            iCountErrorTxt = iCountErrorTxt + 1;
                            infodeta = "Ingrese dato campo adicional";
                        }
                        else {
                            infodeta = "";
                            if (error.name.indexOf("CodigoAdd") != -1 || error.name.indexOf("Código") != -1) {
                                if (iCountErrorCodig == 0) {
                                    infodeta = "Código";
                                    iCountErrorCodig = iCountErrorCodig + 1;
                                }
                                else {
                                    infodeta = "";
                                }
                            }
                            else {
                                infodeta = error.name;
                            }
                        }
                    }
                    if (infodeta != "")
                        infoAdd += "<li  type='square'>" + infodeta + "</li>";
                });
                if (nCountGrid == "true")
                {
                    infoAdd += "<li type='square'>Puntos de georeferencia</li>";
                }
                infoAdd += "</ol>";
                Ext.Msg.show({
                    title: 'Aviso',
                    msg: infoAddPlus + 'Datos invalidos,ingrese datos obligatorios:' + infoAdd,
                    buttons: Ext.Msg.ERROR,
                    animEl: 'elId'
                });
            }
        }
        return (flag);
    } catch (jsbug) {
        AppGlobalJs.showBug("SetValidInfo: " + jsbug);
        return (false);
    }
};
//Habilitar boton y grid una vez que expediente este creado del tab 2 de documentos
//Caso evento <NUEVO>
var ShowMsgEnabledTab2 = function (_msg, _evt) {
    try
    {

        if (_evt == "NUEVO") {
            //Obtener el gridpanel del tab 2
            var cpm = App.tabPanelExp.items.getAt(1).down().down("gridpanel");
            if (cpm) {

                cpm.store.reload();
            }
            //Obtener el button del tab 2
            cpm = App.tabPanelExp.items.getAt(1).down().down("button");
            if (cpm) {

                cpm.enable();
            }
        }
        if (_msg != '') {
            Ext.Msg.show({
                title: 'Aviso',
                msg: _msg,
                buttons: Ext.Msg.OK,
                animEl: 'elId'
            });
        }

    } catch (jsbug) {
        AppGlobalJs.showBug("ShowMsgEnabledTab2: " + jsbug)
    }
};

var showBtnSubirArchivos = function () {
    cpm = App.tabPanelExp.items.getAt(1).down().down("button");
    if (cpm) {
        cpm.show();
        cpm.enable();
    }
};

var selectTreeCheck = function (me, checked, item) {
    try {
        var list = me.getCheckedNodes();
        var node = null;
        if (list.length != 0) {
            node = list[list.length - 1];
        }
        /*
        if (me.lock)
        {
            return;
        }
        */
        var selNodes = me.getChecked();
        Ext.each(selNodes, function (node) {
            node.toggleCheck(false);
        });
        if (checked) {
            if (!me.checkedNode) {
                me.checkedNode = node;
            }
            else {
                //me.lock = true;
                //me.checkedNode.ui.toggleCheck(false);
                //me.toggleCheck(false);
                //me.lock = false;
                me.checkedNode = node;
            }
        }
        else {
            me.checkedNode = null;
        }
        me.dropDownField.setValue(node.text, false);

    } catch (jsbug) {
        AppGlobalJs.showBug("selectTreeCheck: " + jsbug)
    }
};
var checkComentario = function (txtarea, item) {
    try {
        if (txtarea.disabled) {
            txtarea.enable();
            Ext.net.ResourceMgr.registerIcon(["TableEdit"]);
            item.setIconCls("icon-tableedit");
            item.setTooltip({ text: "Incorrecto. Agregue comentario con detalle de información" });
            txtarea.allowBlank = false;
        }
        else {
            txtarea.disable();
            Ext.net.ResourceMgr.registerIcon(["Accept"]);
            item.setIconCls("icon-accept");
            item.setTooltip({ text: "Correcto" });
            txtarea.setValue('');
            txtarea.allowBlank = true;
        }



    } catch (jsbug) {
        AppGlobalJs.showBug("checkComentario: " + jsbug);
    }
};
var checkSiNoMenuComentario = function (hdVal, item, me, txtarea) {
    try {

        hdVal.setValue(item.text);
        me.up('splitbutton').setText(item.text);
        if (item.text == 'No') {
            if (txtarea.disabled) {
                txtarea.enable();

            }
            txtarea.allowBlank = true;
        }
        else {
            txtarea.disable();
            txtarea.allowBlank = false;
        }
    } catch (jsbug) {
        AppGlobalJs.showBug("checkSiNoMenuComentario: " + jsbug);
    }
};
//Eventos de Edicion
var addTab = function (tabPanel, index, menuItem) {
    try {
        tabPanel.setActiveTab(index);
    } catch (jsbug) {
        AppGlobalJs.showBug("addTab: " + jsbug);
    }
};

var TestFormOk = function (items) {
        try {
            //
            var iN = 0;
            for (var index in items) {
              
                var value = App.frmExpediente.getForm().findField(index);
            if (typeof value.id == "undefined") {
                    iN = iN + 1;
                    console.log(value);
                }
            }
        if (iN == 0)
                console.log('Names de Form---->Ok');

        } catch (jsbug) {
            AppGlobalJs.showBug("TestFormOk: " + jsbug)
        }
};

/*
var MostrarControl = function (item, newValue, oldValue, control, numfield) 
{
  try {
      var numOpc = -1;
      if (newValue) {
          numOpc = 1;
          control.show();
          control.enable();//Tambien se habilita en getFormData del formulario
      }
      else {
          control.hide();
          control.disable();
      }
      setCountNF(numfield, numOpc);

  } catch (jsbug) {
      AppGlobalJs.showBug("MostrarControl: " + jsbug);
  }
};
*/